<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
chdir(realpath(dirname(__FILE__)));

require_once('include/entryPoint.php');
require_once('modules/Opportunities/OpportunityFormBase.php');
require_once('include/Gruper/Request.php');
require_once('include/TimeDate.php');

$timedate = new TimeDate();
$request = new Request();

global $sugar_config;

if(empty($current_language)) {
	$current_language = $sugar_config['default_language'];
}

$app_list_strings = return_app_list_strings_language($current_language);
$app_strings = return_application_language($current_language);

global $current_user;

//get User
$current_user = new User();
if($current_user->getByEmail($_POST['con_email'], 'Users') == null){
    echo Request::DEAL_INVALID_USER;
    exit;
}

//get Account
$account = new Account();
if($account->getByEmail($_POST['account_email'], 'Accounts') == null){
    if($account->getByNip($_POST['nip']) == null){
        echo Request::DEAL_INVALID_ACCOUNT;
        exit;
    }
}
//check SIG
$sig_posted = $_POST['sig'];
unset($_POST['sig']);
if(empty($sig_posted) || $request->createSig($_POST) != $sig_posted){
    echo Request::DEAL_INVALID_SIG;
    exit;
}

$_POST['account_id'] = $account->id;
$_POST['account_name'] = $account->name;
$_POST['sales_stage'] = "Closed Won";
$_POST['assigned_user_id'] = $current_user->id;

$_POST['date_closed'] = date($timedate->get_date_format(), $_POST['date_closed']);

$_POST['module'] = "Opportunities";
$_POST['relate_to'] = "Opportunities";
$_POST['probability'] = "100";
$_POST['description'] = $_POST['name'];

$opportunityForm = new OpportunityFormBase();
try{
    $opp = $opportunityForm->handleSave('', false, false);
    if(!empty($opp->id)){
        echo Request::DEAL_CREATED;
    }else{
        echo Request::DEAL_NOT_CREATED;
    }
}catch(Exception $e){
    echo Request::DEAL_NOT_CREATED;
}

$exit_on_cleanup = true;
sugar_cleanup($exit_on_cleanup);
exit;
